//
//  GroupTableViewGroup.m
//  etionUI
//
//  Created by wangjian on 8/12/13.
//
//

#import "GroupTableViewGroup.h"

@interface CGroupTableViewGroup()

@property (nonatomic, retain) UIImageView *bgImageView;
@property (nonatomic, retain) NSMutableArray *separators;
@property (nonatomic, assign) UIEdgeInsets bgEdgeInsets;

@end

@implementation CGroupTableViewGroup

@synthesize contentView = _contentView;
@synthesize separatorSize = _separatorSize;
@synthesize separatorColor = _separatorColor;
@synthesize cells = _cells;

@synthesize bgImageView = _bgImageView;
@synthesize separators = _separators;
@synthesize bgEdgeInsets = _bgEdgeInsets;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.separatorSize = 1;
        self.separatorColor = [UIColor colorWithHex:0xd2d8df];
    }
    return self;
}

- (UIView *)contentView
{
    if (_contentView == nil)
    {
        _contentView = [[UIView alloc] initWithFrame:self.bounds];
        _contentView.layer.masksToBounds = YES;
        _contentView.backgroundColor = [UIColor clearColor];
        [self addSubview:_contentView];
    }
    return _contentView;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    _contentView.backgroundColor = backgroundColor;
}

- (UIImageView *)bgImageView
{
    if (_bgImageView == nil)
    {
        _bgImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        [self insertSubview:_bgImageView atIndex:0];
    }
    return _bgImageView;
}

- (NSMutableArray *)separators
{
    if (_separators == nil)
    {
        _separators = [[NSMutableArray alloc] init];
    }
    return _separators;
}

- (void)dealloc
{
    [_contentView release];
    [_separatorColor release];
    [_cells release];
    
    [_separators release];
    [_bgImageView release];
    [super dealloc];
}

- (void)setGroupBackgroundImageWithImage:(UIImage *)image borderEdgeInsets:(UIEdgeInsets)borderEdgeInsets cornerRadius:(CGFloat)cornerRadius
{
    self.bgImageView.image = image;
    self.bgEdgeInsets = borderEdgeInsets;
    self.contentView.frame = CGRectMake(borderEdgeInsets.left, borderEdgeInsets.top, self.width-borderEdgeInsets.left-borderEdgeInsets.right, self.height-borderEdgeInsets.top-borderEdgeInsets.bottom);
    self.contentView.layer.cornerRadius = cornerRadius;
}

- (void)resetGroupSizeWithContentHeight:(CGFloat)contentHeight
{
    self.frame = CGRectMake(self.left, self.top, self.width, contentHeight+self.bgEdgeInsets.top+self.bgEdgeInsets.bottom);
    self.bgImageView.frame = self.bounds;
    self.contentView.frame = CGRectMake(self.bgEdgeInsets.left, self.bgEdgeInsets.top, self.width-self.bgEdgeInsets.left-self.bgEdgeInsets.right, self.height-self.bgEdgeInsets.top-self.bgEdgeInsets.bottom);
}

- (void)setGroupWithCells:(NSMutableArray *)cells
{
    if (self.cells.count > 0)
    {
        [self.cells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [obj removeFromSuperview];
        }];
    }
    if (self.separators.count > 0)
    {
        [self.separators enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [obj removeFromSuperview];
        }];
        [self.separators removeAllObjects];
    }
    self.cells = cells;
    NSUInteger rowNumber = self.cells.count;
    __block CGFloat contentH = 0;
    [self.cells enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        CGroupTableViewCell *cell = obj;
        cell.frame = CGRectMake(0, contentH, self.contentView.width, cell.height);
        [self.contentView addSubview:cell];
        contentH += cell.height;
        
        UIView *separatorView = [[[UIView alloc] initWithFrame:CGRectMake(cell.separatorInset.left, contentH-self.separatorSize, self.contentView.width, self.separatorSize)] autorelease];
        separatorView.backgroundColor = self.separatorColor;
        [self.contentView addSubview:separatorView];
        [self.separators addObject:separatorView];
        
        if (idx == rowNumber-1)
        {
            separatorView.alpha = 0;
        }
//        else
//        {
//            contentH += self.separatorSize;
//        }
    }];
    [self resetGroupSizeWithContentHeight:contentH];
}

#pragma mark - edit

- (CGSize)resizeCells
{
    //prepare reload
    CGSize groupSize = self.frame.size;
    [UIView animateWithDuration:GROUP_TABLE_VIEW_ANIMATION_DURATION animations:^{
        CGFloat contentH = 0;
        for (NSInteger i=0; i<self.cells.count; i++)
        {
            CGroupTableViewCell *cell = [self.cells objectAtIndex:i];
            UIView *separatorView = [self.separators objectAtIndex:i];
            cell.top = contentH;
            separatorView.top = contentH+cell.height-separatorView.height;

            contentH += cell.height;
        }
        [self resetGroupSizeWithContentHeight:contentH];
    } completion:^(BOOL finished) {
    }];
    
    return groupSize;
}

- (CGSize)reloadCells:(NSArray *)cells atRows:(NSArray *)rows withRowAnimation:(UITableViewRowAnimation)animation
{
    //prepare reload
    CGSize groupSize = self.frame.size;
    NSMutableArray *oldCells = [NSMutableArray array];
    for (NSInteger i=0; i<rows.count; i++)
    {
        NSUInteger row = [[rows objectAtIndex:i] integerValue];
        CGroupTableViewCell *newCell = [cells objectAtIndex:i];
        CGroupTableViewCell *oldCell = [self.cells objectAtIndex:row];
        [oldCells addObject:oldCell];
        [self.cells replaceObjectAtIndex:row withObject:newCell];
        
        newCell.frame = CGRectMake(0, oldCell.top, self.contentView.width, newCell.height);
        newCell.alpha = 0.0;
        [self.contentView insertSubview:newCell aboveSubview:oldCell];
        
        groupSize.height += newCell.height-oldCell.height;
    }
    
    void(^fun1)()=^
    {
        for (CGroupTableViewCell *newCell in cells)
        {
            newCell.alpha = 1.0;
        }
        for (CGroupTableViewCell *oldCell in oldCells)
        {
            oldCell.alpha = 0.0;
        }
        CGFloat contentH = 0;
        for (NSInteger i=0; i<self.cells.count; i++)
        {
            CGroupTableViewCell *cell = [self.cells objectAtIndex:i];
            UIView *separatorView = [self.separators objectAtIndex:i];
            cell.top = contentH;
            separatorView.top = contentH+cell.height-separatorView.height;
            
            NSInteger oldCellIndex = [rows indexOfObject:[NSNumber numberWithInteger:i]];
            if (oldCellIndex != NSNotFound)
            {
                CGroupTableViewCell *oldCell = [oldCells objectAtIndex:oldCellIndex];
                oldCell.top = contentH;
            }
            
            contentH += cell.height;
        }
        [self resetGroupSizeWithContentHeight:contentH];
    };
    void(^fun2)()=^
    {
        for (CGroupTableViewCell *oldCell in oldCells)
        {
            [oldCell removeFromSuperview];
        }
    };
    
    
    if(animation==UITableViewRowAnimationNone)
    {
        fun1();
        fun2();
    }
    else
    {
        [UIView animateWithDuration:GROUP_TABLE_VIEW_ANIMATION_DURATION animations:^
        {
            fun1();
        } completion:^(BOOL finished)
        {
            fun2();
        }];
    }
    
    return groupSize;
}


- (void)prepareInsertCells:(NSArray *)insertCells atRows:(NSArray *)insertRows withRowAnimation:(UITableViewRowAnimation)animation
{
    NSMutableArray *insertSeps = [NSMutableArray array];
    for (NSInteger i=0; i<insertRows.count; i++)
    {
        NSUInteger insertRow = [[insertRows objectAtIndex:i] integerValue];
        CGroupTableViewCell *inserCell = [insertCells objectAtIndex:i];
        CGFloat startY = - inserCell.height;
        if (insertRow > 0)
        {
            CGroupTableViewCell *preCell = [self.cells objectAtIndex:insertRow-1];
            startY = preCell.bottom - inserCell.height;
        }
        inserCell.frame = CGRectMake(0, startY, self.contentView.width, inserCell.height);
        inserCell.alpha = 0;
        [self.contentView addSubview:inserCell];
        
        UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, startY+inserCell.height-self.separatorSize, self.contentView.width, self.separatorSize)];
        separatorView.backgroundColor = self.separatorColor;
        separatorView.alpha = 0.0;
        [self.contentView addSubview:separatorView];
        [insertSeps addObject:separatorView];

        [self.cells insertObject:inserCell atIndex:insertRow];
        [self.separators insertObject:separatorView atIndex:insertRow];
        
        [separatorView release];
    }
}

- (void)startInsertAnimation:(UITableViewRowAnimation)animation
{
    CGFloat contentH = 0;
    for (NSInteger i=0; i<self.cells.count; i++)
    {
        CGroupTableViewCell *cell = [self.cells objectAtIndex:i];
        UIView *sepView = [self.separators objectAtIndex:i];
        
        cell.frame = CGRectMake(cell.left, contentH, cell.width, cell.height);
        cell.alpha = 1.0;
        sepView.frame = CGRectMake(sepView.left, contentH+cell.height-sepView.height, sepView.width, sepView.height);
        if (i == self.cells.count-1)
        {
            sepView.alpha = 0.0;
        }
        else
        {
            sepView.alpha = 1.0;
        }
        
        contentH += cell.height;
    }
    
    [self resetGroupSizeWithContentHeight:contentH];
}

- (void)deleteRows:(NSDictionary *)dicRows withRowAnimation:(UITableViewRowAnimation)animation
{
    CGFloat contentH = 0;
    UIView *lastSepView = nil;
    for (NSInteger cellId = 0; cellId < self.cells.count; cellId++)
    {
        CGroupTableViewCell *cell = [self.cells objectAtIndex:cellId];
        UIView *separator = nil;
        separator = [self.separators objectAtIndex:cellId];
        if ([dicRows objectForKey:[NSNumber numberWithInteger:cellId]] != nil)
        {
            cell.frame = CGRectMake(cell.left, contentH-cell.height, cell.width, cell.height);
            cell.alpha = 0.0;
            separator.frame = CGRectMake(separator.left, contentH-separator.height, separator.width, separator.height);
            separator.alpha = 0.0;
        }
        else
        {
            cell.frame = CGRectMake(cell.left, contentH, cell.width, cell.height);
            contentH += cell.height;
            separator.frame = CGRectMake(separator.left, contentH-separator.height, separator.width, separator.height);
            lastSepView = separator;
        }
    }
    if (lastSepView != nil && lastSepView.alpha > 0)
    {
        lastSepView.alpha = 0.0;
    }
    [self resetGroupSizeWithContentHeight:contentH];
}

- (void)deleteRowsAnimationComplete:(NSDictionary *)dicRows
{
    NSMutableArray *delCell = [NSMutableArray array];
    NSMutableArray *delSep = [NSMutableArray array];
    for (NSInteger cellId = 0; cellId < self.cells.count; cellId++)
    {
        if ([dicRows objectForKey:[NSNumber numberWithInteger:cellId]] != nil)
        {
            [[self.cells objectAtIndex:cellId] removeFromSuperview];
            [[self.separators objectAtIndex:cellId] removeFromSuperview];
            [delCell addObject:[self.cells objectAtIndex:cellId]];
            [delSep addObject:[self.separators objectAtIndex:cellId]];
        }
    }
    [self.cells removeObjectsInArray:delCell];
    [self.separators removeObjectsInArray:delSep];
}

@end
